<template>
  <div class="login-container" v-loading="loading">
    <div class="JPdom" ref="JPdom"></div>
    <div
      v-if="!notFound"
      class="login-center"
      ref="loginCenter"
      :style="{
        backgroundImage: `url(${loginBgUrl})`,
        backgroundRepeat: 'no-repeat',
        backgroundSize: 'cover',
      }"
    >
      <div class="login-data" v-show="name == '登录'">
        <header>账户登录</header>
        <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          label-width="95px"
          size="default"
          label-position="top"
        >
          <el-form-item prop="phonenum" label="账号/手机号" class="text-item">
            <el-input
              placeholder="账号/手机号"
              name="phonenum"
              v-model="form.phonenum"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码" class="text-item">
            <el-input
              placeholder="密码"
              name="password"
              type="password"
              show-password
              v-model="form.password"
            >
            </el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12" class="col m-0 p-0">
              <el-button
                class="login-btn"
                type="primary"
                size="large"
                @click="regAndLogin()"
              >
                登录
              </el-button>
            </el-col>
            <!-- <el-col :span="12" class="col m-0 p-0">
                            <el-button class="forget-pwd" text size="large" @click="name = '忘记密码'">
                                忘记密码
                            </el-button>
                        </el-col> -->
          </el-row>
        </el-form>
      </div>

      <!-- 忘记密码 -->
      <div class="login-data" v-show="name == '忘记密码'">
        <header>忘记密码</header>
        <div class="col" v-show="name == '忘记密码'">
          <el-form
            ref="forgetref"
            :model="forget"
            label-width="95px"
            size="default"
            label-position="top"
          >
            <el-form-item class="text-item" label="手机号：" prop="phonenum">
              <el-input
                placeholder="请输入手机号"
                name="phonenum"
                v-model="forget.phonenum"
              ></el-input>
            </el-form-item>
            <el-form-item class="text-item" label="验证码：" prop="yzm">
              <div class="row m-0">
                <div class="col p-0">
                  <el-input
                    placeholder="四位验证码"
                    v-model="forget.yzm"
                  ></el-input>
                </div>
                <div class="col">
                  <el-button
                    style="margin-top: 0"
                    class="login-btn"
                    type="primary"
                    size="default"
                    @click.stop.prevent="click2"
                    :disabled="time2 !== 60"
                    v-text="time2 == 60 ? '验证码' : time2"
                  ></el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item class="text-item" label="新密码：" prop="password">
              <el-input
                placeholder="请输入新密码"
                name="newpassword"
                type="password"
                show-password
                v-model="forget.password"
              ></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12" class="col m-0 p-0">
                <el-button
                  class="login-btn"
                  type="primary"
                  size="large"
                  @click="forgetpassword"
                  >修改密码</el-button
                >
              </el-col>
              <el-col :span="12">
                <el-button
                  class="forget-pwd"
                  text
                  size="large"
                  @click="name = '登录'"
                  >返回登录</el-button
                >
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
    <div v-else class="not-found">
      <span>团队不存在</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElForm, ElMessage, FormInstance } from "element-plus";
import JParticles, { Particle } from "jparticles";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncgetregistphoneVerificationCode,
  asyncHdbmUserRegist,
  asynclogin,
  asyncresetpassword,
} from "../../api/index";
import { Storekey } from "../../interface";
import { isPhonenum } from "../../util/RegExp";

const store = useStore(Storekey);
const router = useRouter();
const time2 = ref(60);

// 0 学生  1 老师
const name = ref("登录");

const hdbmTeamId = 1929;
const defaultPassword = "000000";
const defaultPhonenum = "10000000000";
const form = reactive({
  password: defaultPassword,
  phonenum: defaultPhonenum,
  teamid: hdbmTeamId,
  name: "",
  username: "",
});
const loginForm = ref<FormInstance>();
const rules = ref({
  phonenum: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      message: "手机号不合法",
      regexp: /^1[3456789]\d{9}$/,
      trigger: "blur",
    },
  ],
  password: [{ required: true, message: "请输入密码", trigger: "change" }],
});
async function regAndLogin() {
  const { phonenum, password } = form;
  try {
    // 注册
    await asyncHdbmUserRegist(form);
    // 登录
    await asynclogin({ ID: phonenum, password, teamid: hdbmTeamId });
    // set store-user
    await store.dispatch("actiononline");
    ElMessage.success("登录成功");
    router.push({ name: "主页" });
  } catch (e: any) {
    console.log("catch login error=>", e);
    ElMessage.error(String(e));
  }
}

//
const notFound = ref(false);
const loginCenter = ref();
const loginBgUrl = ref(
  "https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/saas-login.png"
);
const JPdom = ref();
const jpdata = ref<Particle>();
function jp() {
  if (JPdom.value) {
    jpdata.value = new JParticles.Particle(JPdom.value, {
      color: "#fff",
      proximity: 90,
      range: 100,
      num: 0.1,
      maxR: 2.4,
      minR: 0.6,
      maxSpeed: 0.8,
      minSpeed: 0.1,
    });
  }
}

const loading = ref(false);
function getUrlQuery() {
  const url = new URL(window.location.href);
  const hash = url.hash.substring(1); // 移除 #
  const params = new URLSearchParams(hash.split("?")[1]); // 提取查询参数
  const phonenum = params.get("phone") || defaultPhonenum;
  const name = params.get("name") || "";
  form.phonenum = "hdbm-" + phonenum;
  form.name = name;
  form.username = name;
  console.log("phonenum", phonenum);
  console.log("name", name);
}
onMounted(async () => {
  loading.value = true;
  // getTeamInfo()
  jp();
  // 自动填充
  getUrlQuery();
  // 自动注册 自动登录
  await regAndLogin();
  loading.value = false;
});
onUnmounted(() => {
  jpdata.value?.onDestroy();
  jpdata.value = undefined;
});

// 忘记密码
const forgetref = ref<typeof ElForm>();
const forget = reactive({
  phonenum: "",
  password: "",
  yzm: "",
});
// 验证码
async function click2() {
  const { phonenum } = forget;
  if (time2.value !== 60) return;
  if (isPhonenum.test(phonenum)) {
    await asyncgetregistphoneVerificationCode(phonenum);
    const x = setInterval(() => {
      time2.value = time2.value - 1;
      if (time2.value == 0) {
        clearInterval(x);
        time2.value = 60;
      }
    }, 1000);
  }
}
async function forgetpassword() {
  try {
    const { phonenum, password } = forget;
    await asyncresetpassword(forget);
    ElMessage.success("修改个人信息成功");
    // 是否自动登录
    form.phonenum = phonenum;
    form.password = password;
    name.value = "登录";
  } catch (e: any) {
    ElMessage.error(e);
  }
}
</script>

<style scoped>
.login-container {
  display: grid;
  height: 100vh;
  width: 100vw;
  align-content: center;
  position: relative;
  overflow: hidden;
  /* margin-top: -10px; */

  --el-radio-text-color: #fff;
}

.not-found {
  position: relative;
  text-align: center;
  color: var(--sass-color-blue);
  font-weight: bolder;
  font-size: 50px;
}

.login-center {
  width: 932px;
  height: 540px;
  background-image: url(https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/guanwang/science2.png);
  background-repeat: no-repeat;
  background-size: cover;
  margin: auto;
  box-shadow: 0px 4.8px 14.4px rgba(0, 0, 0, 0.18),
    0px 25.6px 57.6px rgba(0, 0, 0, 0.22);
  border-radius: 8px;
  z-index: 1;
  display: flex;
}

.login-data {
  width: 442px;
  padding: 48px;
  color: #fff;
  --color-43: #fff;
}

.login-data header {
  font-weight: 700;
  font-size: 36px;
  margin-bottom: 48px;
}

/* 登录按钮 */
.login-btn {
  width: 148px;
  border-radius: 4px;
  /*  */
  margin-top: 20px;
}

/* 忘记密码 */
.forget-pwd {
  width: 148px;
  border-radius: 4px;
  /*  */
  margin-top: 20px;
  color: #fff !important;
}

.btn-login1 {
  width: 148px;
  color: #fff;
  background: #1b3694;
  border-radius: 2px;
}

.btn-login2 {
  width: 148px;
  color: #fff;
  background: #17b44c;
  border-radius: 2px;
}

.btn-login3 {
  width: 148px;
  color: #fff;
  background: #17b44c;
  border-radius: 2px;
}

.text-item {
  margin-bottom: 24px;
  color: #fff;
}

.JPdom {
  position: fixed;
  height: calc(100vh + 64px);
  width: 100vw;
  background-color: var(--sass-color-blue3);
}

.login-text {
  margin-left: 48px;
  width: 217px;
  height: 33px;
  background: #164065;
  text-align: center;
  box-shadow: 0px 1.2px 3.6px rgba(0, 0, 0, 0.1);
  color: #fff;
  line-height: 32px;
  margin-top: 140px;
}
</style>

<style>
#app.ojSass .login-container .login-btn:hover {
  color: #fff !important;
  border-color: #fff !important;
  background-color: rgba(0, 0, 0, 0) !important;
  outline: 0;
}

#app.ojSass .login-container .el-button.is-text:not(.is-disabled):focus,
.el-button.is-text:not(.is-disabled):hover {
  background-color: transparent !important;
}
</style>
